import {
  // getWorkflowApprovalHistoryApprovalProcessInstanceIdV2ByProcessInstanceId,
  // IGetWorkflowApprovalHistoryApprovalProcessInstanceIdV2ByProcessInstanceIdRes,
  postDecisionFlowGetProcessDetail,
  getOpProtectionHistoryRecordQueryReassignByHistoryId
} from '@/api';

// import { useCurrentTaskInfo, TApprovalConclusion } from '@/hooks/useCurrentTaskInfo';
import { TApprovalConclusion } from '@/hooks/useCurrentTaskInfo';

import { ComputedRef, InjectionKey, Ref } from 'vue';
import { useMode } from './useMode';
export { useAddSign } from './useAddSign';
import { px2Rem } from '@/utils/rem';
import { useAppStore } from '@/store/app';
import { useGetTaskId } from './useTaskId';
// TODO 移动审批组件
// import { useAppEnv, useMobileApproveTab } from '@/views/app';
// TODO
// import emitter from '@numa/common/utils/emitter';

export type TApprovalViewMode = 'edit' | 'view';
export type TApprovalHistoryData = IGetWorkflowApprovalHistoryApprovalProcessInstanceIdV2ByProcessInstanceIdRes;
export type TApprovalTaskItem = Required<TApprovalHistoryData>['taskActivities'][0];
export type TApprovalStartActivity = Required<TApprovalHistoryData>['startActivity'];
export type TApprovalEndActivity = Required<TApprovalHistoryData>['endActivity'];
export type TApprovalCarbonCopies = Required<TApprovalStartActivity>['carbonCopies'];
export type TApprovalComment = Required<TApprovalHistoryData>['commentList'][0];

interface IApprovalCtx {
  processInstanceId: Ref<string>; // 用于查询 taskId 提交审批、加签
  businessKey: Ref<number | string>; // 业务id， 用于查询审批进度 和 提交审批结论
  progressData: Ref<TNullable<TApprovalHistoryData>>; // 审批进度数据
  isApprovalReject: ComputedRef<boolean>; // 是否被驳回
  navWidth: ComputedRef<string>;
  hasApproval: Ref<boolean>; // 是否存在审批
  approvalConclusion: Ref<TApprovalConclusion>;
  isComplete: Ref<boolean>; // 审批组件是否加载完成
  detailMode: Ref<TApprovalViewMode>; // 内容组件 展示状态
  approvalMode: Ref<TApprovalViewMode>; // 审批组件 展示状态
  isSubmitUser: Ref<boolean>; // 是否为提交人
  isApprovalUser: Ref<boolean>; // 是否为审批人
  loading: Ref<boolean>; // 审批组件 loading，用于刷新页面时加载
  /* 审批完成后 刷新审批组件 ｜ 关闭页面 */
  completeHandleType: 'refresh' | 'close';
  getApprovalProgress: TAnyFunction<Promise<void>>;
  isAllow: Ref<boolean>; // 审批按钮权限
  taskId: Ref<number | string>; // 审批任务id
}
// 审批状态： 拒绝 | 通过 | 系统自动取消 | 超时自动同意 | 超时自动驳回 | 不同意
export type TApprovalStatus = 'REJECT' | 'AGREE' | 'AUTO_CANCEL' | 'OVERDUE_AGREE' | 'OVERDUE_REJECT' | 'DISAGREE';

const ApprovalKey = 'ApprovalKey' as unknown as InjectionKey<IApprovalCtx>;

export const approvalRefreshEventName = 'ApprovalRefreshEventName';
export const ApprovalWidth = px2Rem('264px');

export const useApprovalProvide = () => {
  const approvalCtx = inject(ApprovalKey, null)!;
  return approvalCtx;
};

const useProcessInstanceId = (processInst?: Ref<string>) => {

  const processInstanceId = computed(() => {
    return processInst?.value ;
  });
  return {
    processInstanceId
  };
};

// 使用审批组件前需要先调用，用于初始化数据
export const useApproval = (
  completeCb?: TAnyFunction,
  processInst?: Ref<string>,
  completeHandleType?: IApprovalCtx['completeHandleType']
) => {

  const { detailMode, approvalMode, initMode, isSubmitUser, isApprovalUser } = useMode();
  const isComplete = ref(false);
  const route = useRoute();

  // TODO 移动审批
  // const { isApp, mobileApproveTab } = useMobileApproveTab();
  const isApp = false;
  const mobileApproveTab = { active: 'approve', isHideApprove: true };

  const reaolltInsId = ref('');
  onMounted(() => {
    const historyId = route.query.recordId as string;
    if (historyId) {
      getOpProtectionHistoryRecordQueryReassignByHistoryId({ historyId }).then((res) => {
        reaolltInsId.value = res;
      });
    }
  });

  const adpatorProcessInst = computed(() => {
    return reaolltInsId.value || processInst?.value || '';
  });

  const { processInstanceId } = useProcessInstanceId(adpatorProcessInst);

  const businessKey = ref('');

  const progressData = ref(null as TNullable<TApprovalHistoryData>);
  // 是否已经被回退
  const isApprovalReject = computed(() => {
    return ['DISAGREE', 'REJECTED', 'REVOKED'].includes(approvalConclusion.value);
  });
  // 是否存在审批记录
  const hasApproval = ref(false);
  // 审批状态
  const approvalConclusion = ref<TApprovalConclusion>('');
  // 当前导航栏的宽度
  const navWidth = computed(() => {
    return hasApproval.value ? ApprovalWidth : px2Rem('140px');
  });
  const taskId = ref('');
  // 获取审批节点信息
  const getApprovalProgress = () => {
    return postDecisionFlowGetProcessDetail({
      flowId: processInstanceId.value
    }).then((data) => {
      const res = data.data || {};
      progressData.value = res;
      allowApprove(res);
      taskId.value = useGetTaskId(res);
      approvalConclusion.value = (res.historicProcessInstance?.approvalConclusion as TApprovalConclusion) || '';
      hasApproval.value = !!approvalConclusion.value;
      businessKey.value = res.historicProcessInstance?.businessKey + '';
    });
  };
  
  // 审批按钮权限
  const isAllow = ref(false);
  const allowApprove = (data: any) => {
    const appStore = useAppStore();
    if (data && Array.isArray(data.taskActivities)) {
      let isAllowValue = true;

      for (const taskActivity of data.taskActivities) {
        if (Array.isArray(taskActivity.userTasks)) {
          for (const userTask of taskActivity.userTasks) {
            const assigneeUsers = userTask?.assigneeUsers || [];
            
            if (Array.isArray(assigneeUsers)) {
              // 检查是否存在一个与当前用户匹配且审批状态不为'AGREE'的用户任务
              const matchedUserWithNonAgreeStatus = assigneeUsers.some(item => item.userId === appStore.mcisaas.userBaseId && userTask.approvalStatus !== 'AGREE');
              if (matchedUserWithNonAgreeStatus) {
                isAllowValue = false;
                break; // 找到符合条件的任务后，跳出循环
              }
            }
          }
        } else {
          continue;
        }

        // 如果isAllowValue已经变为false，则无需继续遍历其他taskActivities
        if (!isAllowValue) {
          break;
        }
      }

      isAllow.value = isAllowValue;
    } else {
      isAllow.value = false;
    }
  };

  // 初始化审批进度数据、组件权限
  const initData = async () => {
    isComplete.value = false;
    const isFetchData = (function () {
      if (!isApp) {
        return true;
      }
      return isApp && mobileApproveTab.isHideApprove === false;
    })();
    if (processInstanceId.value && isFetchData) {
      try {
        await getApprovalProgress();
      } catch (e) {}
    }
    // 初始化审批组件的模式
    initMode(approvalConclusion.value, progressData.value!);
    // 审批组件加载完成
    isComplete.value = true;
    completeCb?.();
  };

  // 如果是通过 props 传入的可能是异步，需要监听
  watch(
    processInstanceId,
    () => {
      initData();
    },
    {
      immediate: true
    }
  );
  const loading = ref(false);
  const ctx: IApprovalCtx = {
    processInstanceId,
    loading,
    progressData,
    isApprovalReject,
    navWidth,
    hasApproval,
    approvalConclusion,
    isComplete,
    detailMode,
    approvalMode,
    isSubmitUser,
    isApprovalUser,
    businessKey,
    completeHandleType: completeHandleType ?? 'close',
    getApprovalProgress,
    isAllow,
    taskId
  };
  provide(ApprovalKey, ctx);

  // emitter.on(approvalRefreshEventName, async () => {
  //   // 通过 props 传入需要手动更新，拓展流程通过 FlowControl 组件更新
  //   if (processInst?.value) {
  //     loading.value = true;
  //     await initData();
  //     loading.value = false;
  //   }
  // });

  // onUnmounted(() => {
  //   if (processInst?.value) {
  //     emitter.off(approvalRefreshEventName);
  //   }
  // });

  return ctx;
};

export const isApprovalReject = (status: string) => {
  return ['DISAGREE', 'REJECTED', 'REVOKED'].includes(status);
};
export const isApprovalPass = (status: string) => {
  return ['PASSED', 'REVOKED'].includes(status);
};
